package br.com.cjweb.email.controller;

import java.sql.Connection;

import br.com.cjweb.email.javabean.EmailBean;
import br.com.cjweb.email.model.EmailModel;
import br.com.cjweb.util.controller.AbstractController;
import br.com.cjweb.util.exception.AlterarObjetoException;
import br.com.cjweb.util.exception.CampoRequeridoException;
import br.com.cjweb.util.exception.ClasseNaoEncontradaException;
import br.com.cjweb.util.exception.ConexaoException;
import br.com.cjweb.util.exception.DeletarObjetoException;
import br.com.cjweb.util.exception.EmailException;
import br.com.cjweb.util.exception.GerarSequenceException;
import br.com.cjweb.util.exception.InserirObjetoException;
import br.com.cjweb.util.validar.ValidarEmail;
import br.com.cjweb.util.validar.ValidarObjeto;

public class EmailController extends AbstractController
{
	public EmailController() throws ConexaoException, ClasseNaoEncontradaException
	{
		super();
	}

	public EmailController(Connection conexao) throws ConexaoException
	{
		super(conexao);
	}
	
	private void campoRequeridoEmail(final EmailBean emailBean) throws CampoRequeridoException
	{
		if (emailBean != null)
		{
			if (!ValidarObjeto.isStringValida(emailBean.getEmailDescricao()))
				throw new CampoRequeridoException("Campo email requerido");
		}
	}

	public void inserirEmail(final EmailBean emailBean) throws InserirObjetoException, EmailException, GerarSequenceException, CampoRequeridoException
	{
		EmailModel emailModel = null;
		try
		{
			if (emailBean != null)
			{	
				campoRequeridoEmail(emailBean);
				ValidarEmail.validarEmail(emailBean.getEmailDescricao());
				emailModel = new EmailModel(getConexao());
				emailModel.inserirEmail(emailBean);
			}
		}
		catch(InserirObjetoException e)
		{	
			throw e;
		}
		catch (GerarSequenceException e)
		{
			throw e;
		}
		finally
		{
			if (emailModel != null)
				emailModel = null;
		}
	}
	
	public void alterarEmail(final EmailBean emailBean) throws EmailException, AlterarObjetoException, CampoRequeridoException
	{
		EmailModel emailModel = null;
		try
		{
			if (emailBean != null)
			{	
				campoRequeridoEmail(emailBean);
				ValidarEmail.validarEmail(emailBean.getEmailDescricao());
				emailModel = new EmailModel(getConexao());
				emailModel.alterarEmail(emailBean);
			}
		}
		catch(AlterarObjetoException e)
		{
			throw e;
		}
		finally
		{
			if (emailModel != null)
				emailModel = null;
		}
	}
	
	public void deletarEmail(final EmailBean emailBean) throws DeletarObjetoException
	{
		EmailModel emailModel = null;
		try
		{
			if (emailBean != null)
			{	
				emailModel = new EmailModel(getConexao());
				emailModel.deletarEmail(emailBean);
			}
		}
		catch(DeletarObjetoException e)
		{
			throw e;
		}
		finally
		{
			if (emailModel != null)
				emailModel = null;
		}
	}
	
}
